package com.ruoyi.framework.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import javax.annotation.PostConstruct;
import java.util.concurrent.Executor;

@Configuration
@EnableAsync
public class AsyncTaskPoolConfig {
    @Value("${production.cpuCores:48}")
    private int cpuCores;

    // 核心线程池大小
    private int corePoolSize;

    // 最大可创建的线程数
    private int maxPoolSize;

    @PostConstruct
    public void initConfig() {
        corePoolSize = cpuCores * 10;
        maxPoolSize = cpuCores * 13;
    }

    @Bean("asyncTaskExecutor")
    public Executor checkAliveExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setMaxPoolSize(maxPoolSize);
        executor.setCorePoolSize(corePoolSize);
        // 队列最大长度
        int queueCapacity = 8000;
        executor.setQueueCapacity(queueCapacity);
        // 线程池维护线程所允许的空闲时间
        int keepAliveSeconds = 300;
        executor.setKeepAliveSeconds(keepAliveSeconds);
        executor.setThreadNamePrefix("asyncTask-");
        executor.setWaitForTasksToCompleteOnShutdown(true);
        executor.initialize();
        return executor;
    }
}
